﻿<?php
class Thread{

	private $requisicao, $nomeArquivo, $fp, $host, $port;

	public function __construct($host = '127.0.0.1', $port = 80){

		$this->host =& $host;
		$this->port =& $port;
		$this->nomeArquivo = $_SERVER['SCRIPT_NAME'];
	}

	public function requisicao($func, $arg = false){

		if($arg){

			$this->requisicao .= '&_arrayParams='.urlencode(serialize(&$arg));
		}

		$this->requisicao = '_thread=1&_executar='.urlencode(&$func).$this->requisicao;
	}

	public function iniciar(){

		$this->fp =& fsockopen($this->host, $this->port);
		fwrite(&$this->fp, 'POST '.$this->nomeArquivo." HTTP/1.1\r\nHost: ".$this->host."\r\nContent-type: application/x-www-form-urlencoded\r\nContent-length: ".mb_strlen(&$this->requisicao)."\r\nConnection: close\r\n\r\n".$this->requisicao);
	}

	public function retorno(){

		$flag = false;

		while(!feof($this->fp)) {

			$buffer =& fgets(&$this->fp, 4096);

			if($flag){

				$output .= $buffer;
			}

			if(trim($buffer) == ''){

				$flag = true;
			}			
		}

		$buffer = NULL;
		fclose(&$this->fp);
		return trim(&$output);
	}
}

if(isset($_POST['_thread'])){

	$arg = array();
	$a =& unserialize($_POST['_arrayParams']);

	if(isset($a)){

		foreach($a as $argument){

			$arg[] = $argument;
		}
	}

	$f = $_POST['_executar'];
	unset($_POST['_thread'], $_POST['_arrayParams'], $_POST['_executar']);
	echo call_user_func_array(&$f, &$arg);
	exit;
}
?> 